SQL aliases are used to give a table or column in a table a temporary name.
Aliases are often used to make column names more readable.
An alias exists only for the duration of the current request.
An alias is created using the AS keyword.
SELECT column_name AS alias_name
FROM table_name
SELECT column_name(s)
FROM table_name AS alias_name
Below is a sample from the table "Customers" ("Customers"):
CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
---|---|---|---|---|---|---|
1 | Alfreds Futterkiste | Maria Anders | Obere Str. 57 | Berlin | 12209 | Germany |
2 | Ana Trujillo Emparedados y helados | Ana Trujillo | Avda. de la Constitución 2222 | México D.F. | 5021 | Mexico |
3 | Antonio Moreno Taquería | Antonio Moreno | Mataderos 2312 | México D.F. | 5023 | Mexico |
And the sample from the table "Orders" ("Orders"):
ProductID | OrderID | CustomerID | EmployeeID | OrderDate | ShipperID |
---|---|---|---|---|---|
1 | 10248 | 90 | 5 | 1996-07-04 | 3 |
2 | 10249 | 81 | 6 | 1996-07-05 | 1 |
3 | 10250 | 34 | 4 | 1996-07-08 | 2 |
The following SQL statement creates two aliases, one for the CustomerID column and one for the CustomerName column:
Run SQLSELECT CustomerID AS ID, CustomerName AS Customer
FROM Customers
The following SQL statement creates two aliases: one for the CustomerName column and one for the ContactName column.
Note: It requires double quotes or square brackets if the alias contains spaces:
Run SQLSELECT CustomerName AS Customer, ContactName AS 'Contact Person'
FROM Customers
The following SQL statement creates an alias named "Address" ("Address") that concatenates four columns (address, zip code, city, and country):
SELECT CustomerName, Address + ', ' + PostalCode + ' ' + City + ', ' + Country AS Address
FROM Customers
To make the above SQL statement work in MySQL, use the following:
Run SQLSELECT CustomerName, CONCAT(Address,', ',PostalCode,', ',City,', ',Country) AS Address
FROM Customers
To make the above SQL statement work in Oracle, use the following:
SELECT CustomerName, (Address || ', ' || PostalCode || ' ' || City || ', ' || Country) AS Address
FROM Customers
The following SQL statement selects all orders from the customer with CustomerID = 4 ("Around the Horn"). We use the tables "Customers" and "Orders" and give them table aliases "c" and "o" respectively (here we use aliases to make the SQL query shorter):
Run SQLSELECT o.OrderID, o.OrderDate, c.CustomerName
FROM Customers AS c, Orders AS o
WHERE c.CustomerName = 'Around the Horn' AND c.CustomerID = o.CustomerID
The following SQL statement is the same as above, but without the aliases:
Run SQLSELECT Orders.OrderID, Orders.OrderDate, Customers.CustomerName
FROM Customers, Orders
WHERE Customers.CustomerName = 'Around the Horn' AND Customers.CustomerID = Orders.CustomerID
Aliases can be useful when: